import shortuuid
from flask import request
from  flask_classy import FlaskView, route

from ..models.order import Order
from ..schema.param import checkout_param
from ..schema.resp import currency_not_exist, query_schema, order_list as order_list_resp
from ..services.currency import CurrencyService
from ..services.order import OrderService
from ..services.shop_cart import ShopCartService


def split_order(item):
    return item.offer.dealer_id


# from ..services.
class ShopCartsView(FlaskView):
    @route('/checkout', methods=['POST'])
    def checkout(self):
        data, _ = checkout_param.load(request.get_json())
        currency = None
        if 'currency' in data:
            currency = CurrencyService.get_currency_by_id(data.pop('currency'))
            if not currency:
                return currency_not_exist.jsonify()
        else:
            currency = CurrencyService.get_main_currency()
        from decimal import Decimal
        from itertools import groupby
        cart_items_ids = data.pop('cart_items')
        cart_items = []
        order_list = []
        trade_id = str(shortuuid.uuid()).replace('-', '')
        trade_amount = Decimal.from_float(0.00)
        for id in cart_items_ids:
            cart_item = ShopCartService.get_cart_item(id)
            if not cart_item:
                pass
            cart_items.append(cart_item)

        for _, group in groupby(cart_items, split_order):
            amount = Decimal.from_float(0.00)
            order = OrderService.create_order(currency_id=currency.id,
                                              trade_id=trade_id)
            dealer_id = None
            # print(list(group))
            for item in group:
                dealer_id = item.offer.dealer_id
                order_detail = OrderService.create_order_detail_by_item(item, currency)
                amount += order_detail.amount
                order.details.append(order_detail)
                ShopCartService.mark_item_ordered(item)
            order.amount = amount
            order.dealer_id = dealer_id
            order.status = Order.STATUS_WAIT_PAY
            OrderService.save_order(order)

            order_list.append(order)
            trade_amount += amount
        return query_schema.jsonify_with(items=order_list_resp.dump(order_list).data)
        # fund_channel_id = data.get('fund_channel')
